#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <iostream>


typedef websocketpp::server<websocketpp::config::asio> server_t;

void onOpen(websocketpp::connection_hdl hdl) {
    std::cout << "websocketpp长连接成功\n";
}

void onClose(websocketpp::connection_hdl hdl) {
    std::cout << "wsbsocketpp长连接断开\n"; 
}

void onMessage(server_t* server,websocketpp::connection_hdl hdl,server_t::message_ptr msg) {
    std::string body = msg->get_payload();
    std::cout << "消息：" << body << std::endl;

    //获取到连接的通道，然后send消息
    auto conn = server->get_con_from_hdl(hdl);
    //发送消息
    conn->send(body + "这是一条测试消息",websocketpp::frame::opcode::value::text);
}

int main()
{
    //初始化服务器
    server_t server;
    //关闭日志输出
    server.set_access_channels(websocketpp::log::alevel::none);

    //初始化asio框架
    server.init_asio();

    //设置连接 消息处理  断开的回调函数
    server.set_open_handler(onOpen);
    server.set_close_handler(onClose);
    auto msg_handle = std::bind(onMessage,&server,std::placeholders::_1,std::placeholders::_2);
    server.set_message_handler(msg_handle);

    //设置端口复用
    server.set_reuse_addr(true);

    //设置为监听端口
    server.listen(9090);
    //开始监听
    server.start_accept();
    server.run();

    return 0;
}